from django import forms
from django.core.exceptions import ValidationError
from crm import models
from multiselectfield.forms.fields import MultiSelectFormField
import hashlib


class BSForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            if isinstance(field, (MultiSelectFormField, forms.BooleanField)):
                continue
            field.widget.attrs['class'] = 'form-control'


class RegForm(forms.ModelForm):
    password = forms.CharField(min_length=6,
                               widget=forms.PasswordInput(attrs={'placeholder': '密码', 'autocomplete': 'off'}))
    re_password = forms.CharField(min_length=6,
                                  widget=forms.PasswordInput(attrs={'placeholder': '确认密码', 'autocomplete': 'off'}))

    class Meta:
        model = models.UserProfile
        fields = '__all__'
        exclude = ['is_active']  # 不使用这个字段，在生成数据的时候自动使用默认值

        widgets = {
            'username': forms.TextInput(attrs={'placeholder': '用户名', 'autocomplete': 'off'}),
            'password': forms.PasswordInput(attrs={'placeholder': '密码', 'autocomplete': 'off'}),
            'name': forms.TextInput(attrs={'placeholder': '真实姓名', 'autocomplete': 'off'}),
            'mobile': forms.TextInput(attrs={'placeholder': '手机号', 'autocomplete': 'off'}),
        }

    def clean(self):
        self._validate_unique = True  # 到数据库校验唯一性
        password = self.cleaned_data.get('password')
        re_password = self.cleaned_data.get('re_password')
        if password == re_password:
            try:
                hashlib.md5().update(password.encode('utf-8'))
            except AttributeError:
                pass
            self.cleaned_data['password'] = hashlib.md5().hexdigest()
            return self.cleaned_data
        self.add_error('re_password', '两次密码不一致')
        raise ValidationError('两次密码不一致')


class CustomerForm(BSForm):
    class Meta:
        model = models.Customer
        fields = '__all__'


class ConsultRecordForm(BSForm):

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        customers = models.Customer.objects.filter(consultant=request.user_obj)
        self.fields['customer'].choices = [('', '---------')] + [(i.pk, str(i)) for i in customers]
        self.fields['consultant'].choices = [(request.user_obj.pk, request.user_obj)]

    class Meta:
        model = models.ConsultRecord
        fields = '__all__'


class EnrollmentForm(BSForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        customer_obj = self.instance.customer
        self.fields['customer'].choices = [(customer_obj.pk, customer_obj)]
        self.fields['enrolment_class'].choices = [('', '---------')] + [(i.pk, str(i)) for i in
                                                                        customer_obj.class_list.all()]

    class Meta:
        model = models.Enrollment
        fields = '__all__'


class PaymentRecord(BSForm):
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        customer_obj = self.instance.customer
        self.fields['customer'].choices = [(customer_obj.pk, customer_obj)]
        self.fields['consultant'].choices = [(request.user_obj.pk, request.user_obj)]
        self.fields['enrolment_class'].choices = [('', '---------')] + [(i.enrolment_class.pk, str(i.enrolment_class))
                                                                        for i in
                                                                        models.Enrollment.objects.filter(
                                                                            customer=customer_obj).order_by(
                                                                            'enrolment_class')]

    class Meta:
        model = models.PaymentRecord
        fields = '__all__'


class ClassForm(BSForm):
    class Meta:
        model = models.ClassList
        fields = '__all__'


class CourseRecordForm(BSForm):
    class Meta:
        model = models.CourseRecord
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['re_class'].choices = [(self.instance.re_class_id, self.instance.re_class)]
        self.fields['recorder'].choices = [(self.instance.recorder_id, self.instance.recorder), ]


class StudyRecordForm(BSForm):
    class Meta:
        model = models.StudyRecord
        fields = '__all__'
